package com.wclass.controller;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.wclass.common.ReturnObject;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.oss.QiniuCloudStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-09-08 13:20<br>
 * 描述: ApiUploadController <br>
 */
@Api(description = "文件上传")
@RestController
@RequestMapping("/api/upload")
public class ApiUploadController {

    /**
     * 七牛accessKey
     */
    @Value("${qiniu.accessKey}")
    private String accessKey;
    /**
     * 七牛secretKey
     */
    @Value("${qiniu.secretKey}")
    private String secretKey;
    /**
     * 七牛空间
     */
    @Value("${qiniu.hubName}")
    private String hubName;

    @ApiOperation("获取上传Token")
    @IgnoreAuth
    @RequestMapping("/fileToken")
    public ReturnObject fileToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap putPolicy = new StringMap();
        putPolicy.put("callbackBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        putPolicy.put("callbackBodyType", "application/json");
        long expireSeconds = 3600;
        String upToken = auth.uploadToken(hubName, null, expireSeconds, putPolicy);
        return new ReturnObject(0, "获取成功", upToken);
    }

    /**
     * 上传文件
     */
    @ApiOperation("上传")
    @IgnoreAuth
    @RequestMapping("/file")
    public ReturnObject upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new ReturnObject(1, "上传失败：上传文件不能为空", "");
        }
        QiniuCloudStorageService qiniu = new QiniuCloudStorageService();
        //上传文件
        String url = qiniu.upload(file);
        return new ReturnObject(0, "上传成功", url);
    }
}